<?php

namespace App\Console\Commands;

use App\Libs\BLogger;
use App\Models\AlimamaAcount;
use App\Models\AlimamaOrder;
use App\Models\OrderCommission;
use App\Models\Pid;
use App\Models\PidOrder;
use App\Models\User;
use App\Models\UserPid;
use Illuminate\Console\Command;

class GetAlimamaOrder extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'get-alimama-order';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '从阿里妈妈获取订单';

    protected $url = 'http://pub.alimama.com/report/getTbkPaymentDetails.json?queryType=1&payStatus=&DownloadID=DOWNLOAD_REPORT_INCOME_NEW&';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $startDate = date('Y-m-d', strtotime('-60day'));
        $endDate = date('Y-m-d', time());
        $this->url .= "startTime={$startDate}&endTime={$endDate}";
        $key = [
            "创建时间" => 'create_time',
            "点击时间" => 'click_time',
            "商品信息" => 'title',
            "商品id" => 'tbid',
            "所属店铺" => 'shop_name',
            "商品数" => 'item_num',
            "商品单价" => 'item_price',
            "订单状态" => 'status',
            "订单类型" => 'order_type',
            "收入比率" => 'profit_rate',
            "分成比率" => 'share_rate',
            "付款金额" => 'paid_amount',
            "效果预估" => 'expected_profit',
            "结算金额" => 'settled_amount',
            "预估收入" => 'expected_share',
            "结算时间" => 'settled_time',
            "佣金比率" => 'commission_rate',
            "佣金金额" => 'commission_amount',
            "补贴比率" => 'subsidy_rate',
            "补贴金额" => 'subsidy_amount',
            "补贴类型" => 'subsidy_kind',
            "成交平台" => 'user_agent',
            "第三方服务来源" => 'third_party_service_source',
            "订单编号" => 'order_id',
            "类目名称" => 'category_name',
            "来源媒体id" => 'site_id',
            "广告位id" => 'adzone_id'

        ];

        $account = 'yan乖宝';
        $accountData = AlimamaAcount::where('account', $account)->first();

        if(!$accountData){
            BLogger::getLogger('ALIMAMA_ORDER')->info("{$account}不存在");
        }

        $cookie = $accountData->cookie;
        $data = curlGet($this->url, $cookie);
        if(strpos($data, '<!doctype html>') !== false){
            BLogger::getLogger('ALIMAMA_ORDER')->info("alimama cookie已过期");
            curlPost(env('ALERTOVER_URL'), [
                'source' => 's-7b6f902c-2903-430a-847f-340e87ee',
                'receiver' => 'g-a95d7aec-a227-4e73-9eb4-c5b5bcc9',
                'content' => '阿里妈妈账号登录状态已过期,请及时更换cookie',
                'title' => '阿里妈妈订单更新'
            ]);
            exit;
        }
        $date = date('YmdHi', time());
        $xlsPath = public_path()."/order/order-{$date}.xls";
        file_put_contents($xlsPath,$data);
        \Excel::filter('chunk')->load($xlsPath)->chunk(500, function($results) use($key) {
            $alimamaOrderModel = new AlimamaOrder();
            $saveData = [];
            $saveNum = 0;
            foreach($results as $row) {
                foreach ($row as $okey => $oval){
                    if(isset($key[$okey])){
                        if(
                            $key[$okey] === 'commission_rate'
                            || $key[$okey] === 'subsidy_rate'
                            || $key[$okey] === 'profit_rate'
                            || $key[$okey] === 'share_rate'
                        ){
                            $oval = (str_replace(' %', '', $oval)) / 100;
                        }
                        if($key[$okey] === 'status'){
                            if($oval === '订单失效'){
                                $oval = \Config::get('app.alimama_order.status.invalid');
                            }else if($oval === '订单付款'){
                                $oval = \Config::get('app.alimama_order.status.payment');
                            }else if($oval === '订单结算'){
                                $oval = \Config::get('app.alimama_order.status.settlement');
                            }else if($oval === '订单完成'){
                                $oval = \Config::get('app.alimama_order.status.complete');
                            }
                        }
                        $saveData[$saveNum][$key[$okey]] = $oval;
                    }
                }
                $saveNum ++;
            }

            $pidModel = new Pid();
            $userPidModel = new UserPid();
            $userModel = new User();
            $pidOrder = new PidOrder();
            $orderCommissionModel = new OrderCommission();

            foreach ($saveData as $data){
                \DB::beginTransaction();
                try {
                    $orderId = null;
                    $order = \DB::table($alimamaOrderModel->getTable())->where('order_id', $data['order_id'])->first();
                    if ($order) {
                        $orderId = $order->id;
                        \DB::table($alimamaOrderModel->getTable())->where('order_id', $data['order_id'])->update($data);
                    } else {
                        $orderId = \DB::table($alimamaOrderModel->getTable())->insertGetId($data);
                        $order = (object)$data;
                        $order->id = $orderId;
                    }
                    BLogger::getLogger('ALIMAMA_ORDER')->info("保存订单成功".json_encode($data));
                    $pid = "mm_124555719_{$data['site_id']}_{$data['adzone_id']}";

                    $pidData = \DB::table($pidModel->getTable() . ' as p')
                        ->select(
                            'p.id',
                            'u.agent_level1_rate',
                            'u.agent_level2_rate'
                        )
                        ->leftJoin($userPidModel->getTable() . ' as up', 'p.id', '=', 'up.pid_id')
                        ->leftJoin($userModel->getTable() .' as u', 'u.id', '=', 'up.user_id')
                        ->where('p.pid', $pid)
                        ->lockForUpdate()
                        ->first();

                    if(!$pidData){
                        BLogger::getLogger('ALIMAMA_ORDER')->error("{$pid}不在数据表taoke_alimama_pid里面");
                    }else {
                        if(\DB::table($pidOrder->getTable())->updateOrInsert([
                                'pid_id' => $pidData->id,
                                'order_id' => $orderId,
                            ], [
                                'pid_id' => $pidData->id,
                                'order_id' => $orderId
                            ]) === false){
                            BLogger::getLogger('ALIMAMA_ORDER')->info("保存订单与pid的关系失败,可能已经存在;pid_id:{$pidData->id}, order_id:{$orderId}");
                        }else {
                            BLogger::getLogger('ALIMAMA_ORDER')->info("保存订单与pid的关系成功;pid_id:{$pidData->id}, order_id:{$orderId}");
                        }

                        $commission = [
                            'commission1' => 0,
                            'commission2' => 0
                        ];

                        if(
                            $order->status == \Config::get('app.alimama_order.status.settlement')
                            || $order->status == \Config::get('app.alimama_order.status.complete')
                        ){
                            //已结算订单
                            $commission['commission1'] = bcmul(bcadd($order->commission_amount, $order->subsidy_amount), $pidData->agent_level1_rate);
                            $commission['commission2'] = bcmul(bcadd($order->commission_amount, $order->subsidy_amount), $pidData->agent_level2_rate);
                        }else{
                            //未结算订单
                            $commission['commission1'] = bcmul($order->expected_profit, $pidData->agent_level1_rate);
                            $commission['commission2'] = bcmul($order->expected_profit, $pidData->agent_level2_rate);
                        }

                        if(\DB::table($orderCommissionModel->getTable())->updateOrInsert([
                                'order_id' => $orderId
                            ], $commission) === false
                        ){
                            BLogger::getLogger('ALIMAMA_ORDER')->info("计算订单的佣金,可能已经存在;order_id:{$orderId},commission:".json_encode($commission));
                        }else {
                            BLogger::getLogger('ALIMAMA_ORDER')->info("计算订单的佣金;order_id:{$orderId},commission:".json_encode($commission));
                        }
                    }
                    BLogger::getLogger('ALIMAMA_ORDER')->info("更新订单成功;order_id:{$data['order_id']}");
                    \DB::commit();
                }catch (\Exception $exception){
                    \DB::rollBack();
                    BLogger::getLogger('ALIMAMA_ORDER')->error($exception);
                    BLogger::getLogger('ALIMAMA_ORDER')->error('获取订单失败'.json_encode($data));
                }
            }
        });
    }
}